package web.mb;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;

import metier.entities.Catalogue_prix;
import metier.entities.Client;
import metier.entities.ClientAbonnement;
import metier.entities.Declaration;
import metier.entities.Employe;
import metier.entities.GLN;
import metier.entities.Message;
import metier.entities.Offre;
import metier.entities.Paiement;
import metier.sess.IDeclarationLocal;
import metier.sess.IMessageLocal;
import metier.sess.IOffreLocal;
import metier.sess.IPaiementLocal;
import metier.sess.IStrategiePrixLocal;
import metier.sess.IUtilisateurLocal;


@ManagedBean
@SessionScoped
public class InfoOffreMB {
	
	@EJB
	private IStrategiePrixLocal metierStartegie;
	
	
	@EJB
	private IPaiementLocal metierPaiement;
	
	@EJB
	private IUtilisateurLocal metierUt;
	
	@EJB
	private IDeclarationLocal metierDeclaration;
	
	@EJB
	private IOffreLocal metier;
	
	@EJB 
	private IUtilisateurLocal metierClient;
	
	@EJB 
	private IMessageLocal metierMessage;
	
	//for the session 
	public Offre OFFRE;
	public Declaration DECLARATION;
	
	
	private Offre offre;
	private Integer idOffre;
	
	private boolean messagePayment=false;
    @ManagedProperty(value="#{loginnMB}")
     loginnMB login;
    
    
    //biderr.xhtml
    //minmum bid reduction
    private Double minbid=(double) 12;
    private String autoreverse="0";
    private Double price;
    
    
   //paiement
  //tva est déduite selon le pays de l'utilisateur
  	private Double TVA=(double) 2;
  	private Double prepaid;
  	private  Double desiredPrice;
  	private Double Total;
  	private Integer type=1;
  	private Catalogue_prix s;
  	private Double PreTotal;
    private Integer Rate;
  	private Double rest;
  	
  	
  	
  	//méthode de paiement
  	private boolean paypal;
  	private boolean visa;
  	private boolean bankTransfer;
  	private boolean cash;
  	private boolean cheque;
  	private boolean westernUnion;
  	private boolean moneyGram;
  	private boolean wireTransfer;
  	
  	//declaration
  	private Declaration declaration;
    
    //ce champs permet de faire apparaitre un champs
  	private String paiement="";
    
  	
  	
    public Double getRest() {
		return rest;
	}


	public void setRest(Double rest) {
		this.rest = rest;
	}


	public Integer getRate() {
		return Rate;
	}


	public void setRate(Integer rate) {
		Rate = rate;
	}


	public Double getPrice() {
		return price;
	}


	public void setPrice(Double price) {
		this.price = price;
	}


	public String getAutoreverse() {
		return autoreverse;
	}


	public void setAutoreverse(String autoreverse) {
		this.autoreverse = autoreverse;
	}


	public Double getMinbid() {
		return minbid;
	}


	public void setMinbid(Double minbid) {
		this.minbid = minbid;
	}


	public Declaration getDeclaration() {
		return declaration;
	}


	public void setDeclaration(Declaration declaration) {
		this.declaration = declaration;
	}


	public String getPaiement() {
		return paiement;
	}


	public void setPaiement(String paiement) {
		this.paiement = paiement;
	}


	public boolean isBankTransfer() {
		return bankTransfer;
	}


	public void setBankTransfer(boolean bankTransfer) {
		this.bankTransfer = bankTransfer;
	}


	public Double getTVA() {
		return TVA;
	}


	public void setTVA(Double tVA) {
		TVA = tVA;
	}


	public Double getPrepaid() {
		return prepaid;
	}


	public void setPrepaid(Double prepaid) {
		this.prepaid = prepaid;
	}


	public Double getDesiredPrice() {
		return desiredPrice;
	}


	public void setDesiredPrice(Double desiredPrice) {
		this.desiredPrice = desiredPrice;
	}


	public Double getTotal() {
		return Total;
	}


	public void setTotal(Double total) {
		Total = total;
	}


	public Integer getType() {
		return type;
	}


	public void setType(Integer type) {
		this.type = type;
	}


	public Catalogue_prix getS() {
		return s;
	}


	public void setS(Catalogue_prix s) {
		this.s = s;
	}


	public Double getPreTotal() {
		return PreTotal;
	}


	public void setPreTotal(Double preTotal) {
		PreTotal = preTotal;
	}


	public boolean isPaypal() {
		return paypal;
	}


	public void setPaypal(boolean paypal) {
		this.paypal = paypal;
	}


	public boolean isVisa() {
		return visa;
	}


	public void setVisa(boolean visa) {
		this.visa = visa;
	}


	public boolean isCash() {
		return cash;
	}


	public void setCash(boolean cash) {
		this.cash = cash;
	}


	public boolean isCheque() {
		return cheque;
	}


	public void setCheque(boolean cheque) {
		this.cheque = cheque;
	}


	public boolean isWesternUnion() {
		return westernUnion;
	}


	public void setWesternUnion(boolean westernUnion) {
		this.westernUnion = westernUnion;
	}


	public boolean isMoneyGram() {
		return moneyGram;
	}


	public void setMoneyGram(boolean moneyGram) {
		this.moneyGram = moneyGram;
	}


	public boolean isWireTransfer() {
		return wireTransfer;
	}


	public void setWireTransfer(boolean wireTransfer) {
		this.wireTransfer = wireTransfer;
	}


	public loginnMB getLogin()
    {
    	return login;
    }
    
    
    public void setLogin(loginnMB l)
    {
    	login=l;
    }
	
    
    
    
    
	public boolean isMessagePayment() {
		return messagePayment;
	}


	public void setMessagePayment(boolean messagePayment) {
		this.messagePayment = messagePayment;
	}


	public Integer getIdOffre() {
		return idOffre;
	}



	public void setIdOffre(Integer idOffre) {
		this.idOffre = idOffre;
	}



	public Offre getOffre() {
		return offre;
	}



	public void setOffre(Offre offre) {
		this.offre = offre;
	}

	 private MapModel advancedModel;
	  
	    private Marker marker;

	    public void init() {
	        advancedModel = new DefaultMapModel();
	          
	        //mettre l'altitude et la longitude de l'offre
	        
	        LatLng coord1 = new LatLng(36.879466, 30.667648);
	        LatLng coord2 = new LatLng(36.883707, 30.689216);
	       
	          
	        //Icons and Data
	        advancedModel.addOverlay(new Marker(coord1, "Konyaalti", "konyaalti.png", "http://maps.google.com/mapfiles/ms/micons/blue-dot.png"));
	        advancedModel.addOverlay(new Marker(coord2, "Ataturk Parki", "ataturkparki.png"));
	     }
	  
	    public MapModel getAdvancedModel() {
	        return advancedModel;
	    }
	      
	    public void onMarkerSelect(OverlaySelectEvent event) {
	        marker = (Marker) event.getOverlay();
	    }
	      
	    public Marker getMarker() {
	        return marker;
	    }

	public String  voir(Integer i)
	{
		
		offre=metier.getOffre(i);
		OFFRE=offre;
		idOffre=offre.getIdOffre();
		init();
		return  "InfoOffre.xhtml";
	}
	
	//tester le type de l'utilisateur connecté
	public boolean TestBid()
	{System.out.println("hrt");
		
		if(!login.isLong)
		{
			
			return true;
			
		}
		else if(login.C.getTranExp()=="Tra")
		{
		
			return true;
		
		}
		else
		{
			
			return false;
		}
	}
	
	//bider
    public String MakeABid() throws IOException
    {
    	String redirect="gh";
    	//tester si l'utilisateur est connecté 
    	System.out.println(login.C.getTranExp());
    	if(!login.isLong)
    	{
    	    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "you have to connect press sign In"));
     	   
    	}
    	
    	//si oui tester s'il s'agit d'un transporteur
    	else
    	{
    		
    	if(login.C.getTranExp().compareTo("Tra")==0)
    	{
    		System.out.println("hi tran");
    	/////////////////////////////tester si le transporteur a déja essayé de bider sans saisir le prix en payant///////
    		List<Declaration> dec=metierDeclaration.getNewDeclarationsWithoutPrice(login.C.getIdUtilisateur(), offre);
    		System.out.println(dec.size());
    		if(dec.size()!=0)
    		{
    			////tester si le paiement qui correspond à cett déclaration existe
    			Paiement p=metierPaiement.getPaiementByDeclaration(dec.get(0).getIdDeclaration(), "placing bid",login.C.getIdUtilisateur());
    			if(p!=null)
    			{
    				if(!p.getStatutPaiement())
    				{
    					 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"", "your payment must be confirmed first contact the administrator"));
    			    }
    				else
    				{
    					declaration=dec.get(0);
    					DECLARATION=declaration;
    					redirect="biderr.xhtml";
    				}
    			}
    			
    		}
    		else
    		{
    		
    	/////////////////////////////////tester si le transporteur est abonné////////////////////////
    	int i=0;
    	Client c=(Client)metierUt.getUtilisateur(login.C.getIdUtilisateur());
    	List<ClientAbonnement> abon=c.getCABs();
    	
    		for(i=0;i<abon.size();i++)
    		{
    			if(((abon.get(i).getDateDebut().compareTo(new Date()))<=0) && ((abon.get(i).getDateFin().compareTo(new Date()))>=0)  )
    			{
    	    	   break;
    	      	   
    			}
    		}
    		if( (i>=abon.size()) || (i==0) )
    		{
    			
    			messagePayment=true;
    			paiement="hii";
    			 FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"", "you have to pay press pay"));
    		}
    		else
    		{
    			paiement=" ";
    			FacesContext.getCurrentInstance().getExternalContext().dispatch("bidder.xhtml");
    			redirect="biderr.xhtml";
    			
        }
    		}
       /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    	//si oui 
    	//Tester si sont abonnement est valide
    	//si oui on le redirige vers la page du formulaire
    	//sinon vers la page du paiement puis
    	}
    	else
    		paiement=" ";
    	}
    	
    		
    	
    	System.out.println(redirect);
    	return redirect;
    }
    
    
    
    
    
    
    
    //testpay
    public String pay()
    {
    	System.out.println("iddddd"+login.C.getIdUtilisateur());
    	return  Payer((Client) metierClient.getUtilisateur(login.C.getIdUtilisateur()),null);
    	
    }
    
    //methodes paiements
    
    
    
   //payer lors d'un accept
  public String payaccept(Declaration declaration)
  {
	  return  Payer(login.C,declaration);
  }
  
    
    
  //action payer
  	//i=0 pour le listing , i=1 pour dider
  	public String Payer(Client client,Declaration dec)
  	{
  		
  		if(client.getType_client().compareTo("Pri")==0)
			{
				if(client.getTranExp().compareTo("Tra")==0)
				{
					type=3;
				}
				else
				{
					type=1;
				}
			}
			else
			{
				if(client.getTranExp().compareTo("Tra")==0)
				{
					type=4;
				}
				else
				{
					type=2;
				}
				
			}
  		if(dec==null)
  		{
  		
  		Offre offre=metier.getOffre(idOffre);
  		 //spécifier le type de l'utilisateur
  		 desiredPrice=offre.getPrix_desire();
  		 s=(Catalogue_prix) metierStartegie.getCataloguePrix(offre.getPrix_desire(),type);
  		 System.out.println(s==null);
  		 
  		 if(s==null)
  		 {
  			
  			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "", "the system can't estimate the price  please contact the administrator."));
  			return "a";
  		 }
  		 else
  		 { 
  		 
  		 //pres prix
  		 
  		 prepaid=desiredPrice*(s.getCommission())/100;
  		 Double TotalWT=desiredPrice*(s.getTaux())/100;
  		 
  		 
  		 //total du prix incluant  la tva
  		 Total=TotalWT+TotalWT*TVA/100;
  		 PreTotal=prepaid+prepaid*TVA/100;
  		
  		System.out.println("paiement.xhtml");
  			
  		 }
   		return "Paiement.xhtml";
  		}
  		else
  		{
  			declaration=dec;
  			Paiement p=metierPaiement.getPaiementByDeclaration(dec.getIdDeclaration(), "placing bid",dec.getTransporteur().getIdUtilisateur());
  			desiredPrice=dec.getPrice();
  			rest=p.getMontant();
  			s=(Catalogue_prix) metierStartegie.getCataloguePrix(desiredPrice,type);
  			System.out.println("s");
  	  		 if(s==null)
  	  		 {
  	  			
  	  			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "", "the system can't estimate the price  please contact the administrator."));
  	  		System.out.println("noo");
  	  			return "a";
  	  		 }
  	  		 else
  	  		 { 
  	  			 
  	  		 Rate=s.getTaux();
  	  		 //pres prix
  	  		 
  	  		// prepaid=desiredPrice*(s.getCommission())/100;
  	  		 Double TotalWT=(double) 0;
  	  		 
  	  			 if(desiredPrice>p.getMontant())
  	  			 {
  	  	            TotalWT=(desiredPrice-p.getMontant())*(s.getTaux())/100;
  	  	            
  	  			 }
  	  		 
  	  		 //total du prix incluant  la tva
  	  		 Total=TotalWT+TotalWT*TVA/100;
  	  		// PreTotal=prepaid+prepaid*TVA/100;
  	  		System.out.println("s"+Total);
  	  		 
  	  		 return "../PaiementAccept.xhtml";
  	  		
  	  		 }
  			
  		}
  		 

  		 
  			
  	}
  	
  	//informations affichées
  	
  	public List<String> listeInfo(Integer i)
  	{
  		List<String> l=new  ArrayList<String>();
  		if(i==0)
  		{
  		l.add(" Prepaid Pre-estimated Amount"+PreTotal+".");
  		}
  		else
  			l.add(" Prepaid Pre-estimated Amount"+Total+".");	
  		l.add("When auction is closed the Real Rest Amount to be Paid will be defined.");
  		l.add("When Real Rest Amount to be paid is made of both Shippers and Carriers Information Contact if each other will be communicated by Move Cargo.");
  	    l.add("Shipper and Carrier will make final arrangement between themselves.");
  	    return l;
  	}
  	
  	//
  	public String submitPayment(Long i) throws ParseException
  	{
  		if(i==0)
  			return payer1(null);
  		else
  			return payer1(declaration);
  	}
  	
  	
  	//payer
  	public String payer1(Declaration decl) throws ParseException
  	{
  		//tester si l'une des méthodes est sélectionnée
  		if(!(bankTransfer || paypal || visa || cash || cheque || westernUnion || moneyGram || wireTransfer ))
  		{
  			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "select one payment method"));
  			return  "";
  		
  		}
  		else
  		{
  		String pm = "";
  		if(bankTransfer)
  			pm="bankTransfer";
  		
  		if(paypal)
  			pm="paypal";
  		
  		
  		if(visa)
  			pm="visa";
  		
  		if(cash)
  			pm="cash";
  		
  		if(cheque)
  			pm="cheque";
  		
  		
  		if(westernUnion)
  			pm="westernUnion";
  		
  		if(moneyGram)
  			pm="moneyGram";
  		
  		if(wireTransfer)
  			pm="wireTransfer";
    
  		if(decl==null)
  		{
  		//offre en question 
  		
  		Offre offre=metier.getOffre(idOffre);
  		
  		//date d'expiration
  		   Calendar calendar = Calendar.getInstance();
  	    //définir le format de la date
  	 
  		calendar.add(calendar.DATE,offre.getAuction());
  		
  		Paiement p;
  		Client c=login.C;
  		if(c.getTranExp().compareTo("Tra")!=0)
  		{
  			
  			p=new Paiement("placing bid",pm,new Date(), false, false, PreTotal, metier.getOffre(idOffre));
  				
  		}
  		else
  		{
  			
  			
  			Declaration dec=new Declaration(new Date(),new Double(0),login.C, metier.getOffre(idOffre));
  			dec.setStatut(0);
  			p=new Paiement("placing bid",pm,new Date(), false, false, PreTotal,null);
  			p.setDeclaration(dec);
  			metierDeclaration.addDeclaration(dec);
  			
  		}
    
  		p.setClient(login.C);
  		metierPaiement.addPaiement(p);
  		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "succes paiement"));
  		FacesContext context = FacesContext.getCurrentInstance();
  		context.getExternalContext().getSessionMap().remove("infoOffreMB");
  		}
  		else
  		{
  			
  			Paiement p=new Paiement("Accept Bid",pm,new Date(), false, false, Total,decl.getOffre());
  			p.setDeclaration(decl);
  			p.setClient(login.C);
  			metierPaiement.addPaiement(p);
  			System.out.println("hiiighiez");
  			
  		}
  		
  		if(pm.compareTo("paypal")==0)
  		{
  			return "../Paypal.xhtml";
  		}
  		else if(pm.compareTo("visa")==0)
  		{
  			return "../paiementSage.xhtml";
  		}
  		else
  		{
  			return "../infoPaiement.xhtml";
  		}
  		
  		}
  	}
  	
  	
  	//action biderr.xhtml
  	//onchange autoreverse
  	public void onchangeAutoReverse()
  	{
  		if(autoreverse.compareTo("1")==0)
  		{
  			
  			Double dec=metierDeclaration.MinDeclaration(idOffre);
  			System.out.println(dec);
  			if(dec!=null)
  			{
  				if(dec>minbid)
  				price=dec-minbid;
  				System.out.println(price);
  				
  			}
  			
  		}
  		else
  		{
  			price=(Double)null;
  		}
  		
  	}
  	
  	//make a bid
  	public String bider()
  	{
  		
  		Double MinPric=metierDeclaration.MinDeclaration(idOffre);
  		if(MinPric!=null)
  		{
  			if(price<=0)
  			{
  				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "the price must grater than 0"));
  			    return "here";
  			}
  			else
  			{
	  			if(MinPric > minbid)
	  			{
		  			if(price>MinPric-minbid)
		  			{
		  				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "the price must be less than "+(MinPric-minbid)));
		  			    return "here";
		  			}
	  			}
	  			else
	  			{
	  				
	  				if(price>MinPric)
	  	  			{
	  	  				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "", "the price must be less than "+(MinPric)));
	  	  			    return "here";
	  	  			}
	  				
	  			}
  			
  			
  			}
  		}

  		//ajouter le prix et modifier le statut de la déclaration
  		
  		declaration.setPrice(price);
  		declaration.setStatut(1);
  		metierDeclaration.updateDeclaration(declaration);
  		String a=login.C.getNom()+"  has placed a bid of "+price+" on your listing "+offre.getTitre();
	    //envoyer un message à l'expéditeur
		Message messageExp=new Message("New Bidding info",((Employe)metierClient.getUtilisateur(34)), offre.getExpediteur(), a,new Date());
		Message messageTra=new Message("New Bidding info", ((Employe)metierClient.getUtilisateur(34)),login.C,"This email confirms your bid on the shipment"+offre.getTitre(),new Date());
		metierMessage.addMessage(messageExp);
		metierMessage.addMessage(messageTra);
  		FacesContext context = FacesContext.getCurrentInstance();
  		context.getExternalContext().getSessionMap().remove("infoOffreMB");
  		return "successbiding.xhtml";
  	}
  	
}
